#include "HttpRequest.h"

HttpRequest::HttpRequest(void)
{
}

HttpRequest::~HttpRequest(void)
{
}


bool getToken( const char *&startpos, const char *&tok, unsigned &toklen )
{
	const char *q = startpos;
	tok = q;
	while ( *q != ' ' && *q != '\n'  && *q != '\0' ){
		q++;
	}
	toklen = q-startpos;
	switch ( *q ){
		case '\n':
			*q++;
			toklen++;
			break;
		case ' ':
			*q++;
			break;
		case '\0':
			if ( toklen == 0 )
				return false;
	}
	startpos = q;
	return true;
}

const char* END_LINE = "\r\n";

void HttpRequest::parse( const std::string &request_str)
{
	std::string tmp = request_str;
	const char *q = tmp.c_str();

	const char* tok;
	unsigned toklen;
	getToken( q, tok, toklen );

	if ( strncmp(tok, "GET", toklen ) == 0 ){
		method = METHOD_GET;
	} else if ( strncmp(tok, "POST", toklen ) == 0 ){
		method = METHOD_POST;
	} else {
		status_code = SC_NOT_IMPLEMENTED;
		return;
	}
	
	getToken( q, tok, toklen );
	if ( tok[0] != '/' ){
		status_code = SC_BAD_REQUEST;
		error_dscr = "Failed to parse request. Error in parsing resource requested";
		return;
	}
	resource.clear();
	resource.insert( 0, tok+1, toklen-1 );

	getToken( q, tok, toklen );
	// Get HTTP Version
	if( memcmp( tok, END_LINE, 2 ) !=0 ){
		if( memcmp( tok, "HTTP/", 5 ) == 0 ){
			if( memcmp( tok+5, "1.0", 3 ) == 0){
				version = HTTP_V10;
			} else if ( memcmp( tok+5, "1.1", 3 ) == 0){
				version = HTTP_V11;
			} else {
				status_code = SC_HTTP_VERSION_NOT_SUPPORTED;
				error_dscr = "Failed to parse request. Error in parsing version";
				return;
			}
		} else {
			status_code = SC_BAD_REQUEST;
			error_dscr = "Failed to parse request. Error in parsing version";
			return;
		}
	} else {
		// HTTP 0.9 do not send version.
		version = HTTP_V09;
	}

	while ( !getToken( q, tok, toklen ) ) {
		// Proceed headers.
	}

}